package shujujiegou;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class SocketService2 {
	
	public static void main(String[] args) {
		
//		int port = Integer.valueOf(args[0]);
		int port = 7777;
		try {
			int online = 0;
			ServerSocket server = new ServerSocket(port);
			System.out.println("start server  listen port is " + port);
			while(true){
				final Socket accept = server.accept();
				System.out.println("online:" + (++online));
				
				Thread thread = new Thread(new Runnable(){
					@Override
					public void run() {
						InputStream inputStream = null;
						OutputStream outputStream = null;
							while(true) {
								try {
									//��ȡ�ͻ�������
									inputStream = accept.getInputStream();
									int count = 0;
									while(count == 0) {
										count = inputStream.available();
									}
									byte[] b = new byte[count];
									inputStream.read(b);
									System.out.println(accept.getPort()+"::"+new String(b, 0, count, "utf-8"));
									//��Ӧ�ͻ���
									outputStream = accept.getOutputStream();
									String outmessage = "accept success "+accept.getPort();
									outputStream.write(outmessage.getBytes());
								} catch (IOException e) {
									e.printStackTrace();
								}
//								  finally {
//									try {
//										inputStream.close();
//										outputStream.close();
//									} catch (IOException e) {
//										e.printStackTrace();
//									}
//								}
//								
							}
							
						
					}
				});
				
				thread.start();
				
				
			}
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		
		
		
		
		
	}
	
	
}
